package com.uzai.console.web.pdd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.pdd.pop.sdk.http.PopAccessTokenClient;
import com.pdd.pop.sdk.http.token.AccessTokenResponse;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.pdd.pddtoken.PddTokenCallBackDto;
import com.uzai.console.dto.tb.tbtoken.TbTokenCallBackDto;
import com.uzai.console.entity.PddToken;
import com.uzai.console.entity.TbToken;
import com.uzai.console.service.pdd.PddTokenService;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jianghan
 * @date 2019-06-17 11:39
 */
@Api(value = "多多进宝回调函数",tags = "拼多多|多多进宝", hidden = true)
@RestController
public class PddTokenCallbackController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(PddTokenCallbackController.class);

    @Autowired
    private PddTokenService pddTokenService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    /**
     * 回调获取授权
     * @param code
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "多多进宝刷新授权回调函数", hidden = true)
    @GetMapping("/pdd/callback")
    public void callback(String code,String state) throws Exception {
        logger.info("code:{},state:{}",new Object[]{code,state});

        PopAccessTokenClient accessTokenClient = new PopAccessTokenClient(uzaiConsoleSysConfig.getPddTokenAppkey(), uzaiConsoleSysConfig.getPddTokenAppsecret());
        AccessTokenResponse response = accessTokenClient.generate(code);
        if (StringUtils.isNotBlank(state)){
            int now = DateUtil.getNowTime();
            PddToken pddTokens = new PddToken();
            pddTokens.setId(IdWorker.getId());
            pddTokens.setAccessToken(response.getAccessToken());
            pddTokens.setAuthTime(now);
            pddTokens.setExpiresin(response.getExpiresIn());
            pddTokens.setMerId(Long.parseLong(state));
            pddTokens.setRefreshToken(response.getRefreshToken());
            pddTokens.setUserId(response.getOwnerId());
            pddTokens.setUserName(response.getOwnerName());
            pddTokens.setCreateTime(now);
            pddTokens.setUpdateTime(now);
            pddTokenService.save(pddTokens);
            getResponse().sendRedirect(uzaiConsoleSysConfig.getTokenAuthReturnUrl() + "?state=1");
        } else {
            Map<String,Object> result = new HashMap<>();
            result.put("accesstoken",response.getAccessToken());
            result.put("expiresin",response.getExpiresIn());
            result.put("refreshtoken",response.getRefreshToken());
            result.put("userid",response.getOwnerId());
            result.put("username",response.getOwnerName());
            getResponse().getWriter().write(JSON.toJSONString(result));
        }
    }

    /**
     * 回调获取授权(2.0调用接口）
     * @param
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "平多多联盟刷新授权回调函数(2.0系统调用）")
    @PostMapping("/pdd/oauth")
    public Object pddOauth(@RequestBody PddTokenCallBackDto pddTokenCallBackDto){
        pddTokenService.pddOauth(pddTokenCallBackDto);
        return true;
    }

}
